import Config from "../common/game/config/Config";
import Rect from "../common/game/base/Rect";
import App from "./App";

const { ccclass, property } = cc._decorator;

@ccclass
export default class GameManager extends cc.Component {

    /** 屏幕焦点 */
    static focus: cc.Node = null
    /** 屏幕大小 */
    static screen: Rect
    /** 初始焦点 */
    static initZoom: number = 1.4
    /** 放大倍数 */
    static zoom: number = GameManager.initZoom

    /** 分数显示节点 */
    @property(cc.Node)
    scoreNode: cc.Node = null
    /** 击杀数显示节点 */
    @property(cc.Node)
    killCountNode: cc.Node = null
    @property(cc.Node)
    soundNode: cc.Node = null
    @property(cc.SpriteFrame)
    soundImg: cc.SpriteFrame = null
    @property(cc.SpriteFrame)
    muteImg: cc.SpriteFrame = null

    /** 分数Label */
    scoreLabel: cc.Label = null
    /** 击杀数Label */
    killCountLabel: cc.Label = null

    onLoad() {
        let that = this
        //加载音乐
        cc.loader.loadRes('sound/bgm', cc.AudioClip, (err, res: cc.AudioClip) => {
            let audio = that.getComponent(cc.AudioSource)
            audio.clip = res
            audio.play()
        });

        this.scoreLabel = this.scoreNode.getComponent(cc.Label)
        this.killCountLabel = this.killCountNode.getComponent(cc.Label)
    }

    start() {
        App.ready()
    }

    update(dt) {
        this.displayInfo()
    }

    lateUpdate(dt) {
        this.trackFocus(dt)
    }

    /** 显示分数 */
    displayInfo() {
        if (App.localPlayer && this.scoreLabel) {
            //显示分数
            this.scoreLabel.string = '长度：' + Math.floor(App.localPlayer.score).toString()
        }
    }


    /** 跟踪焦点 */
    trackFocus(dt: number) {

        let focus = GameManager.focus
        if (focus) {

            //平滑跟踪
            let cam = cc.Camera.main
            let smooth = 16 * dt
            cam.node.x = cc.misc.lerp(cam.node.x, focus.x, smooth)
            cam.node.y = cc.misc.lerp(cam.node.y, focus.y, smooth)
            //相机节点
            GameManager.zoom =
                Math.max(0.5, GameManager.initZoom - (focus.scale - Config.snake.initWidth) / 50)
            cam.zoomRatio = cc.misc.lerp(cam.zoomRatio, GameManager.zoom, smooth)
        }
    }

    /** 静音切换 */
    mute() {
        let audio = this.getComponent(cc.AudioSource)
        audio.mute = !audio.mute
        if (audio.mute) {
            this.soundNode.getComponent(cc.Sprite).spriteFrame = this.muteImg
        } else {
            this.soundNode.getComponent(cc.Sprite).spriteFrame = this.soundImg
        }
    }


}
